package com.twu.biblioteca;

import com.twu.biblioteca.exception.ItemUnavailableException;

import java.util.ArrayList;
import java.util.List;

public class Library {

    private static final String SUCCESSFUL_CHECKOUT = "Thank you! Enjoy the item.";
    private static final String UNSUCCESSFUL_CHECKOUT = "That item is not available.";
    private static final String SUCCESSFUL_RETURN = "Thank you for returning the item.";
    private static final String UNSUCCESSFUL_RETURN = "That is not a valid item to return.";

    private List<ItemStatus> itemStatuses;
    private List<User> users;
    private User currentUser;

    public Library(List<ItemStatus> itemStatuses, List<User> users) {
        this.itemStatuses = itemStatuses;
        this.users = users;
    }

    public List<Item> getAvailableItemsOfType(ItemType itemType) {
        List<Item> availableItems = new ArrayList<>();

        for (ItemStatus itemStatus : itemStatuses) {
            if (itemStatus.isAvailableToCurrentUser() && itemStatus.getItem().getItemType().equals(itemType)) {
                availableItems.add(itemStatus.getItem());
            }
        }

        return availableItems;
    }

    public String checkoutItem(String itemName) {
        ItemStatus itemStatus = findItemByName(itemName);
        if (itemStatus != null) {
            try {
                itemStatus.checkout(currentUser);
                return SUCCESSFUL_CHECKOUT;
            } catch (ItemUnavailableException e) {
                return UNSUCCESSFUL_CHECKOUT;
            }
        }
        return UNSUCCESSFUL_CHECKOUT;
    }

    public String returnItem(String itemName) {
        ItemStatus itemStatus = findItemByName(itemName);

        if (itemStatus != null) {
            try {
                itemStatus.returnItem(currentUser);
                return SUCCESSFUL_RETURN;
            } catch (ItemUnavailableException e) {
                return UNSUCCESSFUL_RETURN;
            }
        }

        return UNSUCCESSFUL_RETURN;
    }

    public boolean loginUser(String libraryNumber, String password) {
        for (User user : users) {
            if (user.matches(libraryNumber, password)) {
                currentUser = user;
                return true;
            }
        }
        return false;
    }

    public String getAccountInformation(){
        return currentUser.toString();
    }

    public void updateCurrentUser(User user) {
        this.currentUser = user;
    }

    private ItemStatus findItemByName(String itemName) {
        for (ItemStatus itemStatus : itemStatuses) {
            if (itemStatus.is(itemName)) {
                return itemStatus;
            }
        }
        return null;
    }
}